package dahuiji.resetpassword.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dahuiji.common.entity.User;
import dahuiji.common.servlet.BaceServlet;
import dahuiji.resetpassword.service.ResetPasswordService;

public class ResetPassword extends BaceServlet {

	/**
	 * Constructor of the object.
	 */
	public ResetPassword() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

	@Override
	public String perform(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String result = null;// 注册失败后的提示
		String nextPage = null;// 跳转页面
		String newPassword = request.getParameter("newP");
		ResetPasswordService rps = null;
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("user");
		RequestDispatcher rd;
		if (newPassword == null || newPassword.equals("")) {
			result = "请填写新密码 ";
			nextPage = "/view/resetpassword/resetPassword.jsp";
			request.setAttribute("msg", result);
		} else if (newPassword.length() < 6) {
			result = "密码不能小于6位";
			nextPage = "/view/resetpassword/resetPassword.jsp";
			request.setAttribute("msg", result);
		} else if (user == null) {
			result = "你没有登录，请先登录";
			nextPage = "/view/resetpassword/resetPassword.jsp";
			request.setAttribute("msg", result);
		}else{
			rps = new ResetPasswordService();
			rps.updatePassword(newPassword, user.getId());
			result = "重置成功，请登录";
			nextPage = "/view/login/login.jsp";
			request.setAttribute("msg", result);
		}
		rd = getServletContext().getRequestDispatcher(nextPage);
		rd.forward(request, response);

		return nextPage;
	}

}
